package com.zhiyou100.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.zhiyou100.vo.ResponseVo;
import com.zhiyou100.model.User;
import com.zhiyou100.service.UserService;

@RestController
public class UserController {
	@Autowired
	private UserService userService;
	@GetMapping("/users/{phone}")
	public ResponseVo<User> selectResult(@PathVariable String phone){

		User savedUser = userService.selectAll(phone);

		return new ResponseVo<User>(200,"驗證碼正在發送中",savedUser);
	}
	@PostMapping("/login")
	public ResponseVo<User> loginByCode(@RequestBody User user){

		User savedUser = userService.loginByCode(user);

		return new ResponseVo<>(200,"登陸成功",savedUser);

	}
	@PostMapping("/login")
	public ResponseVo<User> loginByPassword(@RequestBody User user){

		User savedUser = userService.loginByPassword(user);

		return new ResponseVo<>(200,"登陸成功",savedUser);

	}
	@GetMapping("/users/{phone}")
	public ResponseVo<String> selectAll(@RequestBody String phone){
		
		userService.selectAll(phone);
		
		return new ResponseVo<String>(200, "请求成功",null);
		
	}
	@PostMapping("/users")
	public ResponseVo<String> updateAll(User user,MultipartFile file,HttpServletRequest request){
		String web=request.getServletContext().getRealPath("/");
		String path=web+"/"+file.getOriginalFilename();
		
			try {
				file.transferTo(new File(path));
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
			}
		
		user.setPhoto(file.getOriginalFilename());
		userService.updateAll(user);
		return new ResponseVo<String>(200, "修改成功", null);
		
	}

	@PutMapping("/users")
	public ResponseVo<String> updatePassword(@RequestBody User user){
		
		userService.updatePassword(user);
		
		return new ResponseVo<String>(200, "修改成功",null);
		
	}
}
